﻿using System;
using System.Runtime.InteropServices;

namespace TdxApiPool.Invoker
{
    public class DllInvoker
    {

        #region Win API
        [DllImport("kernel32.dll")]
        public static extern IntPtr LoadLibrary(string path);

        [DllImport("kernel32.dll")]
        public static extern IntPtr GetProcAddress(IntPtr lib, string funcName);

        [DllImport("kernel32.dll")]
        public static extern bool FreeLibrary(IntPtr lib);
        #endregion

        protected readonly IntPtr _hLib;

        public DllInvoker(string dllPath)
        {
            _hLib = LoadLibrary(dllPath);
        }

        ~DllInvoker()
        {
            FreeLibrary(_hLib);
        }

        //将要执行的函数转换为委托
        public Delegate Invoke(string apiName, Type t)
        {
            IntPtr api = GetProcAddress(_hLib, apiName);
            return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t);
        }

        public IntPtr GetHandle()
        {
            return _hLib;
        }
            
    }
}
